/*
 * Copyright (C) 2013 Daniel Wasilew <daniel.wasilew@codeminer.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.codeminer.parts.files;

import org.codeminer.parts.application.ApplicationContext;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.AudioHeader;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;
import org.jaudiotagger.tag.datatype.Artwork;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.List;
import java.util.Properties;
import java.util.logging.LogManager;

/**
 *
 * @author Daniel Wasilew <daniel.wasilew@codeminer.org>
 */
class ReadTagsProcessor implements FileProcessor<File> {

    private static final Logger log = LoggerFactory.getLogger(ReadTagsProcessor.class);
    private static final String[] supportedExtensions = {"mp3", "flac", "ogg"};
    private boolean audioTaggerLogDisabled;

    public ReadTagsProcessor() {
    }

    @Override
    public void process(File file, ApplicationContext applicationContext) throws ProcessException {
        try {
            if (!isSupported(file)) {
                throw new ProcessException("Unsupported Fileextension");
            }
            ProcessInfo read = read(file);

            MoveTrackProcessor next = new MoveTrackProcessor();
            next.process(read, applicationContext);

        } catch (IOException | CannotReadException | TagException | ReadOnlyFileException | InvalidAudioFrameException ex) {
            throw new ProcessException("Error while parsing file", ex);
        }
    }

    private ProcessInfo read(File file) throws IOException, CannotReadException, TagException, ReadOnlyFileException, InvalidAudioFrameException {
        if (!audioTaggerLogDisabled) { //disable audiotagger log
            PipedInputStream inputStream = null;
            try {
                Properties properties = new Properties();
                properties.setProperty("org.jaudiotagger.level", "OFF");
                try (PipedOutputStream pipedOutputStream = new PipedOutputStream()) {
                    inputStream = new PipedInputStream(pipedOutputStream);
                    properties.store(pipedOutputStream, null);
                }
                LogManager.getLogManager().readConfiguration(inputStream);
                audioTaggerLogDisabled = true;
            } catch (IOException ex) {
                log.info("could not set audiotagger log level, runs into:", ex);
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException ex) {
                    log.info("could not close inputstream", ex);
                }
            }
        }
        ProcessInfo trackInfo = new ProcessInfo(file);
        AudioFile f = AudioFileIO.read(file);
        Tag tag = f.getTag();
        AudioHeader header = f.getAudioHeader();
        trackInfo.put(ProcessInfo.TrackKeys.DURATION, header.getTrackLength());
        trackInfo.put(ProcessInfo.TrackKeys.BITRATE, header.getBitRate());
        trackInfo.put(ProcessInfo.TrackKeys.CHANNELS, header.getChannels());
        trackInfo.put(ProcessInfo.TrackKeys.FORMAT, header.getFormat());
        if (tag != null) {
            trackInfo.put(ProcessInfo.TrackKeys.ARTIST, getValueOrNull(tag.getFirst(FieldKey.ARTIST)));
            trackInfo.put(ProcessInfo.TrackKeys.ALBUM, getValueOrNull(tag.getFirst(FieldKey.ALBUM)));
            trackInfo.put(ProcessInfo.TrackKeys.YEAR, getValueOrNull(tag.getFirst(FieldKey.YEAR)));
            trackInfo.put(ProcessInfo.TrackKeys.TRACK, getValueOrNull(tag.getFirst(FieldKey.TRACK)));
            trackInfo.put(ProcessInfo.TrackKeys.TITLE, getValueOrNull(tag.getFirst(FieldKey.TITLE)));
            trackInfo.put(ProcessInfo.TrackKeys.GENRE, getValueOrNull(tag.getFirst(FieldKey.GENRE)));
            List<Artwork> artworkList = tag.getArtworkList();
            for (Artwork artwork : artworkList) {
                trackInfo.addArtwork(artwork.getBinaryData());
            }
        } else {
            log.debug("tag == null on [" + file.getAbsolutePath() + "]");
        }
        return trackInfo;
    }

    private boolean isSupported(File file) {
        String fileName = file.getName();
        for (String string : supportedExtensions) {
            if (fileName.toLowerCase().endsWith(string)) {
                return true;
            }
        }
        return false;
    }

    private static String getValueOrNull(String input) {
        if (input == null) {
            return null;
            }
        if (input.trim().isEmpty()) {
            return null;
        } else {
            return input.trim();
        }
    }
}
